document.addEventListener('DOMContentLoaded', function() {
    // 关注按钮交互
    const followButtons = document.querySelectorAll('.follow-btn');
    followButtons.forEach(button => {
        button.addEventListener('click', function() {
            const userId = this.getAttribute('data-user-id');
            
            if (this.classList.contains('following')) {
                // 取消关注
                unfollowUser(userId, this);
            } else {
                // 关注
                followUser(userId, this);
            }
        });
    });
    
    // 关注用户的函数
    function followUser(userId, button) {
        fetch(`/api/users/follow/${userId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        })
        .then(response => {
            // 检查是否未授权（401状态码）
            if (response.status === 401) {
                // 如果未授权，跳转到登录页面
                window.location.href = '/login';
                return Promise.reject(new Error('未授权，请登录'));
            } 
            // 检查是否服务器错误（500状态码）
            else if (!response.ok) {
                throw new Error('服务器响应错误: ' + response.status);
            }
            // 正常处理响应
            return response.json();
        })
        .then(data => {
            if (data.success) {
                button.textContent = '已关注';
                button.classList.add('following');
                // 更新粉丝数
                updateFollowerCount(userId, 1);
            } else {
                alert(data.message);
            }
        })
        .catch(error => {
            // 只有当不是因为未授权而被reject的情况下才显示错误
            if (error.message !== '未授权，请登录') {
                console.error('关注失败:', error);
                alert('关注失败，请稍后重试');
            }
        });
    }
    
    // 取消关注用户的函数
    function unfollowUser(userId, button) {
        fetch(`/api/users/follow/${userId}`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                button.textContent = '关注';
                button.classList.remove('following');
                // 更新粉丝数
                updateFollowerCount(userId, -1);
            } else {
                alert(data.message);
            }
        })
        .catch(error => {
            console.error('取消关注失败:', error);
            alert('取消关注失败，请稍后重试');
        });
    }
    
    // 更新粉丝数
    function updateFollowerCount(userId, change) {
        const userCard = document.querySelector(`[data-user-id="${userId}"]`);
        if (userCard) {
            const followerCountElement = userCard.querySelector('.follower-count');
            if (followerCountElement) {
                let count = parseInt(followerCountElement.textContent);
                count += change;
                followerCountElement.textContent = count;
            }
        }
    }

    // 搜索功能
    const searchInput = document.querySelector('.search-input');
    const userCards = document.querySelectorAll('.user-card');
    
    searchInput.addEventListener('input', function() {
        const searchTerm = this.value.toLowerCase();
        
        userCards.forEach(card => {
            const username = card.querySelector('h3').textContent.toLowerCase();
            const email = card.querySelector('p').textContent.toLowerCase();
            
            if (username.includes(searchTerm) || email.includes(searchTerm)) {
                card.style.display = 'block';
            } else {
                card.style.display = 'none';
            }
        });
    });
    
    // 用户卡片点击跳转到个人资料页面
    userCards.forEach(card => {
        card.addEventListener('click', function(e) {
            // 如果点击的是关注按钮，不跳转
            if (e.target.classList.contains('follow-btn')) {
                return;
            }
            
            const username = this.querySelector('h3').textContent;
            // 这里假设用户详情页的URL格式是 /profile?username=xxx
            window.location.href = `/profile?username=${encodeURIComponent(username)}`;
        });
    });
    
    // 加载更多按钮功能
    const loadMoreBtn = document.querySelector('.load-more');
    loadMoreBtn.addEventListener('click', function() {
        // 模拟加载更多用户的效果
        this.textContent = '加载中...';
        
        setTimeout(() => {
            this.textContent = '没有更多用户了';
            this.disabled = true;
            this.style.backgroundColor = '#f0f0f0';
            this.style.color = '#999';
            this.style.cursor = 'not-allowed';
        }, 1500);
    });
});